import axios from 'axios'
import { ElMessageBox, ElMessage } from "element-plus";
import { getToken, removeToken, rememberRequestAndParam, isRepetRequest, getUserInfo,setLoginFlag } from "@/utils/localStorage";
import saveAs from "file-saver";
import { baseURL } from '@/constant/system.js'

document.title = "万民为天";
const service = axios.create({
  baseURL: baseURL,
  headers: {
    "content-type": "application/json",
  },
  // timeout: 5000, // 超时时间
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = getToken();
    // 添加请求头
    config.headers["Authorization"] = token;
    let userInfo = getUserInfo();
    config.headers["Oss-Origin"] = 1; // 来源=1表示请求来自网页端 , 后端根据角色和学员ID判断请求数据的权限
    if (userInfo) {
      config.headers["Oss-Role"] =  userInfo.roleNameList
      config.headers["Oss-StudentId"] = userInfo.studentID;
      config.headers["Oss-StudentAccount"] = userInfo.studentAccount;
    }
    // 遍历请求参数
    if (config.data) {
      const newParams = {};
      for (let key in config.data) {
        if (config.data[key]) {
          // 参数值的类型
          let keyType = Object.prototype.toString.call(config.data[key]).toLowerCase()
          // 字符串类型的请求参数, 使用trim()去除参数的前后空格
          if (keyType.includes("string")) {
            newParams[key] = config.data[key].toString().trim();
          } else {
            // 其他类型暂不处理, 否则会报错
            newParams[key] = config.data[key];
          }
        } else {
          newParams[key] = config.data[key];
        }
      }
      config.data = newParams;

      //  // 非登录请求校验是否重复请求
      //  if (!config.url.includes("user/login")  &&  !config.url.includes("/user/getUserByToken")) {
      //   // 校验是否重复请求(post请求)
      //   let repetReq = isRepetRequest(config.url,config.data)
      //   if (repetReq == true) {
      //     return Promise.reject(new Error("数据正在处理，请勿重复提交"));
      //   } else {
      //     rememberRequestAndParam(config.url,config.data)
      //   }
      // }
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 未登录的提示弹窗是否关闭 true=关闭  false=没有关闭 , 没有关闭不用再次弹出了
var unLoginBoxClose = true;
// response interceptor 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    console.log("响应=",res);
    // 返回的请求头不是json , 就是二进制数据, 则直接返回
    if ( !response.headers['content-type'].startsWith("application/json")) {
      //handleDownload(response);
      return response;
    } 
    if (res.code !== 1) {
      if (res.code == -1) {
        console.log("未登录提窗框是否关闭=", unLoginBoxClose);
          if (unLoginBoxClose == false) {
          } else {
            unLoginBoxClose = false
            ElMessageBox.confirm("用户未登录或登录状态已失效, 请重新登录...", "", {
              type: "warning",
              draggable: true,
              confirmButtonText: "去登录",
            })
            .then(() => {
              removeToken();
              setLoginFlag(false)
              location.href = "/ossweb/";
            })
            .catch(() => {})
            .finally(()=>{
              unLoginBoxClose = true;
            })
          }
      } else if (res.code == -2) {
        ElMessage.error(res.message);
      } else if (res.code == 0) {
        ElMessage.error({
          message:"操作失败:" + res.message,
          type: "error",
          duration: 5 * 1000,
          showClose:true
        });
      }
      return res;
    } else {
      return res;
    }
  },
  error => {
    console.log("err" , error);
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.resolve(error);
  }
)
// get参数拼接
function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== '' &&
            typeof value[key] !== 'undefined'
          ) {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 */
export function handleDownload(res) {
    const blob = new Blob([res.data], { type: res.headers['content-type'] });
    // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
    const contentDisposition = decodeURI(res.headers['content-disposition']);
    const result = patt.exec(contentDisposition);
    let fileName = result ? result[1] : 'file';
    fileName = fileName.replace(/"/g, '');
    saveAs(blob, fileName);
}

export default service
